package priv.zgh.forum.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import priv.zgh.forum.annotation.CheckToken;
import priv.zgh.forum.annotation.LoginToken;
import priv.zgh.forum.auth.entity.User;
import priv.zgh.forum.auth.service.UserService;
import priv.zgh.forum.exception.ForumException;
import priv.zgh.forum.utils.JwtUtils;
import priv.zgh.forum.utils.MyStringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenInfo = request.getHeader("token");
        // 注解不是在方法上就直接跳过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否有用户注解
        if (method.isAnnotationPresent(CheckToken.class)) {
            CheckToken checkToken = method.getAnnotation(CheckToken.class);
            if (checkToken.required()) {
                // 认证执行
                if (tokenInfo == null) {
                    throw new ForumException(20001,"无token，请重新登录");
                }
                // 取出token有效载荷中的user id
                String userId;
                try {
                    userId = JWT.decode(tokenInfo).getClaim("id").asString();
                } catch (JWTDecodeException j) {
                    throw new ForumException(20001,"访问异常！");
                }
                // 从数据库中取出数据
                User user = userService.getById(userId);
                if (user == null) {
                    throw new ForumException(50008,"用户不存在，请重新登录");
                }
                try {
                    Boolean verify = JwtUtils.isVerify(tokenInfo, user);
                    if (!verify) {
                        throw new ForumException(50008, "非法访问！");
                    }
                }catch (Exception e){
                    throw new ForumException(50008,"非法访问！");
                }

                // 权限判定
                String servletPath = request.getServletPath();
                // 获取用户所有权限信息并且匹配路径信息
                for(String path : userService.getUserAllPowerPath(user)){
                    System.out.println("权限路径:" + path);
                    System.out.println("访问路径:" + servletPath + ",与权限路径:" + path +",的匹配结果为:" +  MyStringUtils.isMatch(servletPath,path));
                    if(MyStringUtils.isMatch(servletPath,path)){
                        return true;
                    }
                }
                System.out.println("用户ID:" + user.getId() + ",对路径:" + request.getServletPath() + ",没有访问权限.");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
